from typing import Any
from langchain.tools import BaseTool, tool
import json
from datetime import datetime
from .database_manager import DatabaseManager


class PaymentTool(BaseTool):
    name = "支付处理工具"
    description = "用于处理支付和订单的工具"
    db_manager: DatabaseManager = None

    def __init__(self, **data):
        super().__init__(**data)
        self.db_manager = DatabaseManager()

    def _run(self, command: str) -> Any:
        """实现BaseTool的抽象方法"""
        try:
            if command.startswith("pay:"):
                _, product_id, quantity = command.split(":")
                return self.tool(int(product_id), int(quantity))
            return "无效的命令格式"
        except Exception as e:
            return f"执行命令错误: {str(e)}"

    def _arun(self, command: str) -> Any:
        """实现BaseTool的异步抽象方法"""
        raise NotImplementedError("暂不支持异步操作")

    @tool("处理支付")
    def tool(self, product_id: int, quantity: int, payment_method: str = None, coupon_id: int = None):
        """
        处理支付的工具
        参数:
            product_id: 商品ID
            quantity: 购买数量
            payment_method: 支付方式（可选）
            coupon_id: 优惠券ID（可选）
        """
        try:
            # 查询商品信息
            results = self.db_manager.execute_query(
                "SELECT * FROM products WHERE id = %s",
                (product_id,)
            )
            
            if not results:
                return json.dumps({
                    "status": "error",
                    "message": "商品不存在"
                }, ensure_ascii=False)
            
            product = results[0]
            
            # 计算总价
            total_amount = product['price'] * quantity
            
            # 如果有优惠券，应用优惠
            if coupon_id:
                coupon_results = self.db_manager.execute_query(
                    "SELECT * FROM coupons WHERE id = %s AND status = 'active'",
                    (coupon_id,)
                )
                
                if coupon_results:
                    coupon = coupon_results[0]
                    if coupon['type'] == 'percentage':
                        discount = total_amount * coupon['discount_value']
                    else:  # dollar type
                        discount = coupon['discount_value']
                    total_amount = max(0, total_amount - discount)
            
            # 如果没有指定支付方式，返回可用的支付方式
            if not payment_method:
                return json.dumps({
                    "status": "payment_methods",
                    "message": "请选择支付方式",
                    "data": {
                        "total_amount": total_amount,
                        "payment_methods": ["现金", "信用卡", "移动支付"]
                    }
                }, ensure_ascii=False)
            
            # 处理支付
            # 这里应该有实际的支付处理逻辑
            # 现在我们假设支付总是成功的
            
            # 记录销售信息
            self.db_manager.execute_update(
                """INSERT INTO sales 
                (product_id, quantity, total_amount, payment_method, coupon_id) 
                VALUES (%s, %s, %s, %s, %s)""",
                (product_id, quantity, total_amount, payment_method, coupon_id)
            )
            
            return json.dumps({
                "status": "success",
                "message": "支付成功",
                "data": {
                    "product_name": product['name'],
                    "quantity": quantity,
                    "total_amount": total_amount,
                    "payment_method": payment_method
                }
            }, ensure_ascii=False)
            
        except Exception as e:
            return json.dumps({
                "status": "error",
                "message": f"支付处理失败: {str(e)}"
            }, ensure_ascii=False)

    def __del__(self):
        if hasattr(self, 'cursor') and self.cursor:
            self.cursor.close()
        if hasattr(self, 'conn') and self.conn:
            self.conn.close()
